package com.bwie.auth.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwie.auth.feign.UserRemoteService;
import com.bwie.auth.service.AuthService;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.User;
import com.bwie.common.domain.response.JwtResponse;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserRemoteService userRemoteService;

    @Override
    public Result userLogin(User user) {
        if(user.getUserName().equals("")){
            return Result.error("用户名不能为空");
        }
        if(user.getUserPwd().equals("")){
            return Result.error("密码不能为空");
        }
        Result<User> result = userRemoteService.userLogin(user);
        User user1 = result.getData();
        if(user1==null){
            return Result.error("用户名或密码错误");
        }
        String userkey = UUID.randomUUID().toString();
        HashMap<String, Object> map = new HashMap<>();
        map.put(JwtConstants.USER_KEY,userkey);
        String token = JwtUtils.createToken(map);
        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+userkey,
                JSONObject.toJSONString(user1),TokenConstants.EXPIRATION, TimeUnit.MINUTES);
        JwtResponse jwtResponse = new JwtResponse();
        jwtResponse.setToken(token);
        jwtResponse.setExpireTimeStr("15MIN");
        return Result.success(jwtResponse);
    }

    @Override
    public User info() {
        String header = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(header);
        String userJSONStr = redisTemplate.opsForValue().get(TokenConstants.LOGIN_TOKEN_KEY + userKey);
        return JSONObject.parseObject(userJSONStr,User.class);
    }

    @Override
    public void logout() {
        String header = request.getHeader(TokenConstants.TOKEN);
        String userKey = JwtUtils.getUserKey(header);
        redisTemplate.delete(TokenConstants.LOGIN_TOKEN_KEY+userKey);
    }

}
